const express = require('express');
const cors = require('cors');
const logger = require('./services/logger');
const mysql = require('./services/mysql');

const app = express();

// 初始化数据库
mysql.init().catch(error => {
    logger.error('数据库初始化失败:', error);
    process.exit(1);
});

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 路由
app.use('/history', require('./routes/history'));
app.use('/monitor', require('./routes/monitor'));

// 错误处理
app.use((err, req, res, next) => {
    logger.error('应用错误:', err);
    res.status(500).json({
        code: 500,
        success: false,
        message: '服务器内部错误',
        error: err.message
    });
});

module.exports = app; 